const scope_list = {
	'scope.userInfo' : {name:'用户信息',error:'用户信息权限异常'},
	'scope.userLocation' : {name:'地理位置',error:'地理位置权限异常'},
	'scope.userLocationBackground' : {name:'后台定位',error:'后台定位权限异常'},
	'scope.address' : {name:'通信地址',error:'通信地址权限异常'},
	'scope.record' : {name:'录音功能',error:'录音功能权限异常'},
	'scope.writePhotosAlbum' : {name:'保存到相册',error:'保存到相册权限异常'},
	'scope.camera' : {name:'摄像头',error:'摄像头权限异常'},
	'scope.invoice' : {name:'获取发票',error:'获取发票权限异常'},
	'scope.invoiceTitle' : {name:'发票抬头',error:'发票抬头权限异常'},
	'scope.werun' : {name:'微信运动步数',error:'微信运动步数权限异常'},
}

const permissionAuth = (scope)=>{
	return new Promise((resolve,reject)=>{
		uni.authorize({
		  	scope: scope,
		  	success:function(res) {
		  		console.log('authorize-success+++++',res)
		  		resolve(true)
		  	},
		  	fail:function(err){
		  		console.log('authorize-fail+++++',err)	
				permission(scope).then(function(){
					resolve(true)
				}).catch(function(res){
					reject(res)
				})
				// reject(err)
		  	}
		})
	})
}

const permission = (scope) => {
	return new Promise((resolve,reject)=>{
		uni.getSetting({
		   success(res) {
			  console.log(res.authSetting)
			  if(res.authSetting[scope]){
				  resolve(true)
			  }else{
				  
				uni.showModal({ 
					icon:"none",
					title:"授权",
					confirmText:"前往",
					content:"前往设置:【"+scope_list[scope].name +"】授权",
					success:function(res) {
						if (res.confirm) {
							console.log('用户点击确认');
							uni.openSetting({
							  success(res) {
								console.log("++openSetting++success++++++",res.authSetting)
								if(res.authSetting[scope]){
									resolve(true)
								}else{
									uni.showToast({ icon:"none", title:"授权异常:"+scope_list[scope].error })
									reject(res)
								}
							  },
							  fail(err){
								  console.log("++openSetting++fail++++++",err)
							  }
							});
						} else if (res.cancel) {
							uni.showToast({ icon:"none", title:"需开启对应权限"})
							console.log('用户点击取消');
						}
					}
				})
				
				// setTimeout(function(){
					
				// },800)
				  
				  
				
				  
				  
			  }
			  
		   },
		   fail(e){
			   uni.showToast({ icon:"none", title:"授权异常.:"+scope_list[scope].error })
		   }
		})
	
		
	}) 
}

export {
	permissionAuth,
	permission,
}